﻿# CoffeeScript

# functions
@getDateTime = ->
    now = new Date();
    year = now.getFullYear();
    month = now.getMonth() + 1;
    day = now.getDate();
    hour = now.getHours();
    minute = now.getMinutes();
    second = now.getSeconds();
    if month.toString().length == 1
        month = '0' + month;
    
    if day.toString().length == 1
        day = '0' + day;

    if hour.toString().length == 1
        hour = '0' + hour;

    if minute.toString().length == 1
        minute = '0' + minute;

    if second.toString().length == 1
        second = '0' + second;

    dateTime = year + '/' + month + '/' + day + ' ' + hour + ':' + minute + ':' + second;
    return dateTime;

@UpdateCss = (cssFile) ->
    $.get("css/stylesheet" + cssFile + ".css?" + pageLoadTime, (data) ->
        styleSheetElement = $("#swappableStyleSheet");

        if styleSheetElement[0].styleSheet
            styleSheetElement[0].styleSheet.cssText = data;
        else
            styleSheetElement.html(data);

        SubtractJS.Initialize().UpdateLayout();
    );

@UpdateHtmlEditor = (templateName) ->
    newHtmlSource = $("#" + templateName).html().split('\n');
    srcLen = newHtmlSource.length - 1;
    output = "";
    for i in [0..srcLen]
        line = newHtmlSource[i];

        if line.length > 8 && line.substring(0, 8) == "        "
            line = line.substring(8, line.length);

        if $.trim(line) != ""
            output += line;
            output += '\n';

    $("#htmlCode").val(output);

    UpdatePreview();

@UpdatePreview = ->
    newHtml = $("#htmlCode").val();

    $("#previewArea").html(newHtml);

    SubtractJS.Initialize().UpdateLayout();

# event handlers
# space between "submit" and "(event" very important
$("form").submit (event) -> 
    event.preventDefault();

$("#cssSelect").change ->
    UpdateCss($(this).val());

$("#updateHtml").click ->
    UpdatePreview;

$(".previewLink").click (event) ->
    event.preventDefault();
    id = $(this).attr("id");
    UpdateHtmlEditor(id + "Sample");


# onload
$(
    UpdateCss("Square");
    UpdateHtmlEditor("headerFooterSample");
);

# global variables
pageLoadTime = getDateTime();

